package club.banyuan.service;

import club.banyuan.entity.User;
import club.banyuan.request.Request;
import club.banyuan.util.Constant;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author edz
 * @version 1.0
 * @date 2020/12/19 下午3:53
 */
public class UserService {
//    private FileService fs;
//    private PageService ps;
private int Maxid=-1;
private  String loginUserName=null;

    public UserService() {
    }

    /**
     * 用户登录
     *
     * @param data
     * @return
     */
    public boolean login(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        //把接收到的data数据转换成user对象用来比较
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        //为什么要用集合，因为集合可以用流的过滤filter方法过滤掉不符合的，
        // 然后用count方法返回此流中的符合过滤条件的元素个数
        long count = userList.stream().filter(user1 -> user1.getName().equals(user.getName())&&user1.getPwd().equals(user.getPwd())).count();
        if (count == 0) {
            System.out.println("登录失败");
            ps.sendData("用户名或密码错误", false, dos);
            return false;
        } else {
            loginUserName=user.getName();
//            System.out.println("--------"+loginUserName);
            System.out.println("登录成功");
            ps.sendData("登录成功", dos);
            return true;
        }
    }

    /**
     * 查询json里面的所有已存储的用户信息
     */
    public List<User> QueryUserJson() {
        FileService fs = new FileService();
        String json = fs.read(Constant.USERS_PATH);
        //转换成user对象集合用来比较
        List<User> usersList = JSONObject.parseArray(json, User.class);
        return usersList;
    }


    /**
     * 获取用户列表信息
     */

    public void getUserList(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        List<User> userList1 = userList.stream().filter(user1 -> user1.getName().contains(user.getName())).collect(Collectors.toList());

        ps.sendData(userList1, dos);
    }

    /**
     * 添加新用户
     *
     * @param data
     * @param dos
     */
    public void addUser(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        if(Maxid==-1){
            int id = userList.stream().max(new Comparator<User>() {
                @Override
                public int compare(User o1, User o2) {
                    return o1.getId() - o2.getId();
                }
            }).get().getId();
            Maxid=id;
        }
        for (int i = 0; i < Maxid; i++) {
            int a = i;
            long count = userList.stream().filter(user1 -> user1.getId() == a).count();
            if (count == 0) {
                Maxid = --i;
                break;
            }
        }
        user.setId(++Maxid);
        user.setUserTypeStr(user.getUserType() == 0 ? "普通用户" : "经理");
        userList.add(user);
        String jsonString = JSONObject.toJSONString(userList);
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(Constant.USERS_PATH))) {
            bw.write(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ps.sendData("操作成功", dos);
    }


    /**
     * 通过id查询指定用户
     *
     * @param data
     * @param dos
     * @throws IOException
     */

    public void getUserById(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        User user2 = userList.stream().filter(user1 -> user1.getId() == user.getId()).findFirst().get();
//        String jsonString = JSONObject.toJSONString(user2);
        ps.sendData(user2, dos);
    }


    /**
     * 通过id修改用户信息
     *
     * @param data
     * @param dos
     * @throws IOException
     */

    public void updateUser(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        //流只能使用一次，但我们修改了流里的数据之后还要再修改List里的user，做不到，
        // 这里只要遍历集合，通过ID找到那一项，用set进行修改
//        User user2 = userList.stream().filter(user1 -> user1.getId() == user.getId()).findFirst().get();
//        if(!user.equals(user2)){
//            user2=user;
//        }
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getId() == user.getId()) {
                userList.set(i, user);
            }
        }
        String jsonString = JSONObject.toJSONString(userList);
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(Constant.USERS_PATH))) {
            bw.write(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ps.sendData("修改成功", dos);
    }


    /**
     * 通过id删除用户
     *
     * @param data
     * @param dos
     * @throws IOException
     */

    public void deleteUser(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        User user = JSONObject.parseObject(data, User.class);
        List<User> userList = QueryUserJson();
        for (int i = 0; i < userList.size(); i++) {
            if (userList.get(i).getId() == user.getId()) {
                userList.remove(i);
            }
        }
        String jsonString = JSONObject.toJSONString(userList);
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(Constant.USERS_PATH))) {
            bw.write(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ps.sendData("删除成功", dos);
    }


    /**
     * 登录成功时将用户姓名显示在"欢迎您"之后
     * @param data
     * @param dos
     * @throws IOException
     */
    public void getUserInfo(String data, DataOutputStream dos) throws IOException {
        PageService ps = new PageService();
        ps.sendData(loginUserName,dos);
    }


    public void userQuit(String data, DataOutputStream dos) {

    }
}
